package controller

import (
	"encoding/base64"
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"sweeter.star/go-demo/common"
	"sweeter.star/go-demo/dao"
	"sweeter.star/go-demo/model"
	"sweeter.star/go-demo/response"
	"sweeter.star/go-demo/util"
)

func Login(ctx *gin.Context) {
	db := common.GetDB()
	// 获取参数
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")

	// 数据验证
	if len(telephone) != 11 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机号必须为11位")
		return
	}
	if len(password) < 6 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码长度不能低于6位")
		return
	}

	// 手机号不存在
	var user model.User
	db.Where("telephone = ?", telephone).First(&user)
	if user.ID == 0 {
		response.Response(ctx, http.StatusUnprocessableEntity, 423, nil, "用户不存在")
		return
	}
	// 密码验证
	enpass, _ := base64.StdEncoding.DecodeString(user.Password)
	log.Println("--- [ PASSWORD 验证 ]", user, enpass)
	if password != string(enpass) {
		response.Response(ctx, http.StatusUnprocessableEntity, 423, nil, "密码验证失败")
		return
	}

	token, err := common.ReleaseToken(user)
	if err != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "系统异常")
		log.Printf("token generate error: %v", err)
		return
	}

	// 登录成功，发放 TOKEN
	response.Successful(ctx, "登录成功", gin.H{"token": token})
}

func Register(ctx *gin.Context) {
	DB := common.GetDB()

	// 获取参数
	name  := ctx.PostForm("name")
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")

	// 数据验证
	if len(telephone) != 11 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机号必须为11位")
		return
	}
	if len(password) < 6 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码长度不能低于6位")
		return
	}

	if len(name) == 0 {
		name = fmt.Sprintf("%s%s", "wx", util.Random(6, util.NUMERIC))
	}

	if isTelephoneExist(DB, telephone) {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "用户已经存在")
		return
	}

	// 新增用户
	newpwd := base64.StdEncoding.EncodeToString([]byte(password))
	log.Println(name, telephone, password, newpwd)
	newUser := model.User{
		Nickname: name,
		Telephone: telephone,
		Password: newpwd,
	}
	DB.Create(&newUser)

	response.Successful(ctx, "注册成功", nil)
}

func User(c *gin.Context)  {
	user, _ := c.Get("user")
	response.Successful(c, "ok", gin.H{
		"user": dao.User(user.(model.User)),
		})
}

func isTelephoneExist(db *gorm.DB, telephone string) bool {
	var user model.User
	db.Where("telephone = ?", telephone).First(&user)
	return user.ID != 0
}